package com.next

import grails.transaction.Transactional
import groovy.transform.CompileStatic
import groovy.transform.TypeChecked

/**
 * @Author 班旭娟
 * @CreatedDate 2017-4-21
 * @ModifiedDate 2017-11-07
 */
@Transactional
@CompileStatic
@TypeChecked
class WorkflowInstanceUserService
{

    static scope = "singleton"
    ProjectTeamService projectTeamService
    AssetTeamService assetTeamService
    IssueTeamService issueTeamService
    ActivityTeamService activityTeamService

    def initWorkflowInstanceUser(WorkflowInstanceStage workflowInstanceStage, WorkflowStage workflowStage)
    {
        def workflowInstanceUser

        def userPositionList

        def workflowUsers = WorkflowUser.findAll("from WorkflowUser where stage.id = ${workflowStage?.id}")

        workflowUsers?.each { workflowUser ->
            userPositionList = UserPosition.findAll("from UserPosition where position.id = :position", [position: workflowUser?.position.id])
            userPositionList?.each { userPosition ->
                workflowInstanceUser = WorkflowInstanceUser.find("from WorkflowInstanceUser where user.id = ${userPosition?.user?.id} and stage.id = ${workflowInstanceStage?.id}")
                if (!workflowInstanceUser)
                {
                    workflowInstanceUser = new WorkflowInstanceUser()
                    workflowInstanceUser.stage = workflowInstanceStage
                    workflowInstanceUser.user = userPosition?.user
                    workflowInstanceUser.authority = workflowUser?.authority
                    workflowInstanceUser.save flush: true

                    if (workflowInstanceStage?.instance?.project)
                    {
                        projectTeamService.initProjectTeam workflowInstanceStage?.instance?.project, userPosition?.user
                    }
                    else if (workflowInstanceStage?.instance?.activity)
                    {
                        activityTeamService.initActivityTeam workflowInstanceStage?.instance?.activity, userPosition?.user
                    }
                    else if (workflowInstanceStage?.instance?.issue)
                    {
                        issueTeamService.initIssueTeam workflowInstanceStage?.instance?.issue, userPosition?.user
                    }
                    else if (workflowInstanceStage?.instance?.asset)
                    {
                        assetTeamService.initAssetTeam workflowInstanceStage?.instance?.asset, userPosition?.user
                    }

                }
            }
        }
    }
}
